package com.cea.papyrus.core.actions;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.eclipse.gef.Disposable;
import org.eclipse.gef.ui.actions.ActionRegistry;
import org.eclipse.jface.action.IAction;

/**
 * Registry able to look in a more global registry (nested editors within a global one)
 */
public class ExtendedActionRegistry extends ActionRegistry {
	
	/** registry for the parent editor, in case of multipart editor */
	protected ActionRegistry parentRegistry;

	/**
	 * Creates a new ActionRegistry, with a link to its parent
	 * @param parentRegistry the registry of the aprent editor
	 */
	public ExtendedActionRegistry(ActionRegistry parentRegistry) {
		this.parentRegistry = parentRegistry;
	}
	
	@Override
	public void dispose() {
		// overrides dispose because super.dispose() uses getActions, and this methods
		// is overriden in this class. It returns actions from this registry and from
		// the parent registry. If dispose is not overriden, then action from the parent
		// editor would also be disposed
		Iterator actions = super.getActions();
		while (actions.hasNext()) {
			IAction action = (IAction)actions.next();
			if (action instanceof Disposable)
				((Disposable)action).dispose();
		}
	}
	
	/* (non-Javadoc)
	 * @see org.eclipse.gef.ui.actions.ActionRegistry#getAction(java.lang.Object)
	 */
	@Override
	public IAction getAction(Object key) {
		IAction action = super.getAction(key);
		if(action == null) {
			return parentRegistry.getAction(key);
		}
		return action;
	}
	
	/* (non-Javadoc)
	 * @see org.eclipse.gef.ui.actions.ActionRegistry#getActions()
	 */
	@Override
	public Iterator<IAction> getActions() {
		Map<String, IAction> map = new HashMap<String, IAction>(15);
		
		// add action from the parent registry
		Iterator<IAction> it = parentRegistry.getActions();
		while (it.hasNext()) {
			IAction action = it.next();
			map.put(action.getId(), action);
		}
		
		// adds action from this registry
		it = super.getActions();
		while (it.hasNext()) {
			IAction action = it.next();
			map.put(action.getId(), action);
		}
		return map.values().iterator();
	}
	
}
